package com.eaglefly.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;

/**
 * 功能：
 * 时间：2018/1/9 18:26
 *
 * @author zhaojinpeng
 */
public class TypeUtils {

    private final static Logger logger = LoggerFactory.getLogger(TypeUtils.class);

    /**
     * 构建class  主要是为了包裹异常
     *
     * @param className
     * @return
     */
    public static Class<?> getClassFromName(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            logger.error("ClassNotFound" + className);
            throw new RuntimeException("ClassNotFound" + className, e);
        }
    }

    /**
     * 构建对象  主要是为了包裹异常
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getNewBean(Class<?> clazz) {
        try {
            return (T) clazz.newInstance();
        } catch (Exception e) {
            logger.error("newInstance Error" + clazz.getName());
            throw new RuntimeException("newInstance Error" + clazz.getName(), e);
        }
    }

    /**
     * 获取父级接口
     *
     * @param clazz
     * @return
     */
    public static Class<?> getInterface(Class<?> clazz) {

        Class<?>[] interfaces = clazz.getInterfaces();
        if (interfaces.length == 0) {
            logger.error("接口" + clazz.getName() + "没有继承Redisson接口");
            throw new RuntimeException("接口" + clazz.getName() + "没有继承Redisson接口");
        } else if (interfaces.length > 1) {
            logger.error("接口" + clazz.getName() + "没有继承了多个接口");
            throw new RuntimeException("接口" + clazz.getName() + "没有继承了多个接口");
        } else {
            return interfaces[0];
        }
    }

}
